<template>
  <div class="student-manage">
    <div class="head">全部用户</div>
    <div class="select-button">
      <el-row>
        <el-col :span="12">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-input v-model="input" placeholder="请输入用户姓名关键词" @change="pageUsers" ></el-input>
            </el-col>
            <el-col :span="12">
              <el-input v-model="inputPhone" placeholder="请输入学员手机号码"  @change="pageUsers"></el-input>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="4" :offset="1">
          <el-select v-model="inputIsBanned" placeholder="用户封禁状态">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="3">
          <el-button  type="primary" icon="el-icon-search" @click="pageUsers()">查询</el-button>
        </el-col>
        <el-col :span="3">
          <el-button  type="primary" icon="el-icon-search" @click="clear()">清空</el-button>
        </el-col>


      </el-row>
    </div>
    <div class="student-list" style="display: flex;flex-direction: column;align-items: center">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="selection" width="55"  align="center">
        </el-table-column>
        <el-table-column fixed prop="id" label="用户ID" min-width="50%" align="center">
        </el-table-column>
        <el-table-column prop="nickname" label="用户昵称" min-width="40%" align="center" >
        </el-table-column>
        <el-table-column prop="tel" label="手机号" min-width="40%" align="center" >
        </el-table-column>
        <el-table-column prop="role" label="角色" min-width="40%" align="center" >
        </el-table-column>
        <el-table-column prop="isBanned" label="封禁状态" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{scope.row.isBanned=='0'?'未封禁':'已封禁'}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="gmtCreate" label="注册时间" min-width="50%" align="center" >
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="250">
          <template slot-scope="scope">
            <el-button @click="beginInfoEdit(scope.row)" type="text" size="medium">编辑</el-button>
            <el-button @click="banUser(scope.row.id)" type="text" size="medium" v-if="scope.row.isBanned == 0">封禁</el-button>
            <el-button @click="unbanUser(scope.row.id)" type="text" size="medium" v-if="scope.row.isBanned == 1">解禁</el-button>
            <el-button type="text" size="medium" @click="beginCourseBind(scope.row.id)">绑定课程</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="block" style="margin-top: 20px">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[8, 10, 20, 40]"
            :page-size="8"
            layout="total, sizes, prev, pager, next, jumper"
            :total="parseInt(total)">
        </el-pagination>
      </div>
    </div>

    <el-dialog title="课程绑定" show-close :visible.sync="courseBindDialogVisible">
      <el-form label-width="120px">
        <el-form-item label="已绑定课程">
          <div style="display: flex;flex-direction: row;flex-wrap: wrap;width: 80%">
            <div v-if="userBindCourseList.length ==0">暂无绑定</div>
            <div v-for="item in userBindCourseList">
              <div>
                <el-popover
                    placement="top-start"
                    title="课程简介"
                    width="200"
                    trigger="hover"
                >
                  {{ item.courseDescription }}
                  <el-button slot="reference">{{ item.courseName }}</el-button>
                </el-popover>
                <el-button style="margin-left: 10px" @click="">{{item.role}}</el-button>
                <el-button @click="unbindCourse(item.courseId)" style="margin-left: 10px;color: red">解绑</el-button>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="选择新课程">
          <el-select v-model="bindCourseIdList" multiple filterable remote
                     reserve-keyword placeholder="请输入课程名关键词" :remote-method="queryCourse" :loading="loading"
                     style="min-width: 450px;">
            <el-option
                v-for="item in queryCourseList"
                :key="item.name"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="绑定角色">
          <el-select v-model="courseBindRole" filterable style="min-width: 450px">
            <el-option
                v-for="(item,index) in CourseUserAllRoles"
                :key="item"
                :label="item"
                :value="index">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="courseBindDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="bindCourse">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="编辑信息" style="width: 70%;margin-left: 15%" show-close :visible.sync="societyInfoDialogVisible">
      <el-form label-width="80px">
        <el-form-item label="姓名">
          <el-input style="max-width: 450px" v-model="currentUserInfo.nickname"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input style="max-width: 450px" v-model="currentUserInfo.tel"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="currentUserInfo.role" filterable style="min-width: 450px">
            <el-option
                v-for="(item,index) in UserAllRoles"
                :key="item"
                :label="item"
                :value="index">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="societyInfoDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateInfo">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "StudentManageView",
  data() {
    return {
      total: 0,
      currentSize: 8,
      currentPage: 1,

      courseBindRole:'',
      courseDescription: "",

      CourseUserAllRoles:["用户","共创者","主理人"],

      UserAllRoles:["普通用户","候浪者","内容共创者，浪者","社区共创者，飓风和暗流","系统管理员，同样为暗流"],

      courseBindDialogVisible: false,
      societyInfoDialogVisible: false,

      currentUserId: "",
      currentUserInfo: {
      },

      bindCourseIdList: [],
      queryCourseList: [],
      userBindCourseList: [],
      departmentTree: null,

      loading: false,

      input: "",
      inputPhone: "",
      inputIsBanned: '',
      debounceClock: null,

      tableData: [],

      options: [{
        value: 0,
        label: '未封禁'
      }, {
        value: 1,
        label: '已封禁'
      }]
    };
  },
  mounted() {
    this.pageUsers();
  },
  methods: {
    pageUsers() {
      this.$api.pageUsers({
        pageSize: this.currentSize,
        pageNow: this.currentPage,
        nickName: this.input || '',
        tel: this.inputPhone || '',
        isBanned : this.inputIsBanned
      })
          .then((res) => {
            let list = res.data.rows;
            this.total = res.data.totalPage
            console.log(this.total)
            this.tableData = list
          });
    },
    handleSizeChange(val) {
      this.currentSize = parseInt(val);
      this.pageUsers();
    },
    handleCurrentChange(val) {
      this.currentPage = parseInt(val);
      this.pageUsers();
    },


    beginCourseBind(userId) {
      this.currentBindUserId = userId
      this.courseBindDialogVisible = true
      this.getUserBindCourseList(userId)
    },

    getUserBindCourseList(userId) {
      this.$api.getUserBindCourseList({
        userId: userId
      }).then(res => {
        this.userBindCourseList = res.data
        console.log(this.userBindCourseList)
      })
    },

    queryCourse(nameKey) {
      this.$api.getCourseList(nameKey).then(res => {
        this.queryCourseList = res.data.rows
      })
    },
    bindCourse() {
      let userIds = [this.currentBindUserId]
      this.$api.bindCourse({
        courseIds: this.bindCourseIdList,
        role: this.courseBindRole,
        userIds: userIds
      }).then(res => {
        console.log(res)
        this.courseBindDialogVisible = false
      })
    },
    unbindCourse(courseId) {
      let currentBindUserId = this.currentBindUserId
      this.$confirm('此操作将永久删除所有学习记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        this.$api.unbindCourse({
          userId: currentBindUserId,
          courseId: courseId
        }).then(res => {
          console.log(res)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getUserBindCourseList(currentBindUserId)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    banUser(userId) {
      console.log({
        userId: userId,
      })
      this.$confirm('确认是否封禁用户', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        this.$api.banUser({
          userId: userId,
        })
            .then(response => {
              this.$message({
                type: 'success',
                message: '封禁成功!'
              });
              this.pageUsers()
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消封禁'
        });
      });
    },
    unbanUser(userId) {
      console.log({
        userId: userId,
      })
      this.$confirm('确认是否解禁用户', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        this.$api.unbanUser({
          userId: userId,
        })
            .then(response => {
              this.$message({
                type: 'success',
                message: '解禁成功!'
              });
              this.pageUsers()
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消解禁'
        });
      });
    },


    beginInfoEdit(userInfo) {
      this.currentUserInfo = {
        nickname: userInfo.nickname,
        tel: userInfo.tel,
        role: userInfo.role,
        id: userInfo.id
      }
      this.societyInfoDialogVisible = true
    },
    updateInfo() {
      this.currentUserInfo.manageRole = this.currentUserInfo.role
      this.currentUserInfo.role = ''
      this.$api.updateInfo(this.currentUserInfo).then(res => {
        this.$message.success("成功！")
        this.societyInfoDialogVisible = false
        this.pageUsers()
      })
    },
    clear(){
      this.inputPhone = ''
      this.input = ''
      this.inputIsBanned = ''
      this.pageUsers();
    }

  },
  watch: {
    input() {
      clearTimeout(this.debounceClock);
      this.debounceClock = null;
      this.debounceClock = setTimeout(() => {
        this.getUsers();
        clearTimeout(this.debounceClock);
        this.debounceClock = null;
      }, 500);
    },
    inputPhone() {
      clearTimeout(this.debounceClock);
      this.debounceClock = null;
      this.debounceClock = setTimeout(() => {
        this.getUsers();
        clearTimeout(this.debounceClock);
        this.debounceClock = null;
      }, 500);
    }
  }
};
</script>

<style scoped>
.student-manage{
  margin-top: 20px;
  width: 100%;
}


.head {
  padding-bottom: 10px;
}

.select-button {
  padding: 10px 0;
}

.student-list {
  width: 100%;
  padding: 10px 0;
  display: flex;
}
</style>
